package com.tiny_wind.tiny_wind_diary.service.impl;


import com.tiny_wind.tiny_wind_diary.dao.DiaryDao;
import com.tiny_wind.tiny_wind_diary.dao.DiaryUnitDao;
import com.tiny_wind.tiny_wind_diary.entity.DiaryEntity;
import com.tiny_wind.tiny_wind_diary.entity.DiaryUnitEntity;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class DiaryServiceImpl {

    private Logger logger = LogManager.getLogger(this.getClass());

    // 注入Service依赖
    @Autowired
    private DiaryDao mDao;
    @Autowired
    private DiaryUnitDao mUnitDao;

    public DiaryEntity[] search(DiaryEntity filter) {
        DiaryEntity[] entity = mDao.search(filter);
        return entity;
    }

    /**
     * 先找DiaryUnit
     * 然后找Diary
     * 然后一起返回.
     * @param filter
     * @return
     */
    public DiaryEntity searchOne(DiaryEntity filter) {
        if(filter.id != 0) {
            DiaryUnitEntity unitFilter = new DiaryUnitEntity();
            unitFilter.diaryId = filter.id;
            DiaryUnitEntity[] units = mUnitDao.search(unitFilter);
            DiaryEntity entity = mDao.searchOne(filter);
            entity.units = units;
            return entity;
        }
        return null;
    }


    public void update(DiaryEntity entity) {
        mDao.update(entity);
    }

    /**
     * 插入日记是一个比较复杂的处理.
     *
     * @param entity
     */
    public void insert(DiaryEntity entity) {
        DiaryUnitEntity[] units = entity.units;
        ArrayList<DiaryUnitEntity> unitList = new ArrayList<>();
        mDao.insert(entity);
        Integer diaryId =  entity.id;
        if (units.length > 0) {
            for (DiaryUnitEntity unit : units) {
                unit.diaryId = diaryId;
                mUnitDao.insert(unit);
//                unitList.add(unit);
            }
            //批量插入拿不到id,改为一次一次插入.
//		int n =mUnitDao.insertArray(units);
//            int n = mUnitDao.insertList(unitList);
            logger.debug("unit result is {}");
        }
    }

    public void delete(DiaryEntity filter) {
        DiaryUnitEntity unitFilter = new DiaryUnitEntity();
        unitFilter.diaryId = filter.id;
        mUnitDao.delete(unitFilter);
        mDao.delete(filter);
    }
}
